# -*- coding: utf-8 -*-

import hashlib
import demjson
import re
import time
import os


def get_md5(url):
    """
    生成MD5值
    """
    if isinstance(url, str):
        url = url.encode("utf-8")
    m = hashlib.md5()
    m.update(url)
    return m.hexdigest()


def get_video_id(value):
    return re.findall(r'videoId:.*?(\d+)', value)


# def get_video_alt_url(value):
#     return re.findall(r'video_alt_url:.\'(.+?).\',', value)
#
#
# def get_video_url(value):
#     return re.findall(r'video_url:.\'(.+?).\',', value)


def get_video_obj(value):
    js_content = re.findall(r'new DPlayer\({[\s\S]*?}\);', value)
    val = js_content[0][12:-2]
    val_container = val.replace(re.findall(r'container:[\s\S].*', val)[0], "")
    try:
        if len(re.findall(r'customType:\s{[\s\S]*?}[\s\S]*?}', val_container)) > 0:
            val_custom_type = val_container.replace(re.findall(r'customType:\s{[\s\S]*?}[\s\S]*?}', val_container)[0], "")
        else:
            val_custom_type = val_container
    except Exception as e:
        print(e)
    return demjson.decode(val_custom_type)


def get_create_time():
    return int(time.time())


def get_key_value(line):
    if line.find('#') == -1:
        arr = line.split('=')
        return arr[0], arr[1]


def get_conf():
    with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/conf/conf.conf', 'r+') as f:
        PPX_HOST, value1 = get_key_value(f.readline())
        PPX_USER, value2 = get_key_value(f.readline())
        PPX_PASSWORD, value3 = get_key_value(f.readline())
        PHPSESSID, value4 = get_key_value(f.readline())
        return {
            PPX_HOST.strip(): value1.strip(),
            PPX_USER.strip(): value2.strip(),
            PPX_PASSWORD.strip(): value3.strip(),
            PHPSESSID.strip(): value4.strip()
        }


def set_conf(new_url):
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    with open(path + '/conf/conf.conf', 'r') as f:
        PPX_HOST, value1 = get_key_value(f.readline())
        PPX_USER, value2 = get_key_value(f.readline())
        PPX_PASSWORD, value3 = get_key_value(f.readline())
        PHPSESSID, value4 = get_key_value(f.readline())
        f.close()

    with open(path + '/conf/conf.conf.tmp', 'w') as fi:
        fi.write('{key}={value}\n'.format(key=PPX_HOST.strip(), value=new_url.strip()))
        fi.write('{key}={value}\n'.format(key=PPX_USER.strip(), value=value2.strip()))
        fi.write('{key}={value}\n'.format(key=PPX_PASSWORD.strip(), value=value3.strip()))
        fi.write('{key}={value}\n'.format(key=PHPSESSID.strip(), value=value4.strip()))
        fi.flush()
        fi.close()

    os.remove(path + '/conf/conf.conf')
    os.rename(path + '/conf/conf.conf.tmp', path + '/conf/conf.conf')
